from django.db import models
from django.utils import timezone
from pinyin import pinyin
from django.core.exceptions import ValidationError
from django.contrib.auth import get_user_model
User = get_user_model()
import os
from ckeditor_uploader.fields import RichTextUploadingField  # 带上传功能的富文本字段
def validate_file_size(value):
    """验证文件大小不超过5MB"""
    filesize = value.size
    if filesize > 10 * 1024 * 1024:  # 5MB
        raise ValidationError("文件大小不能超过5MB")
    allowed_extensions = ['.pdf', '.doc', '.xls', '.xlsx', '.docx']
    ext = os.path.splitext(value.name)[1].lower()
    if ext not in allowed_extensions:
        raise ValidationError('只允许上传PDF和Word.docx/excel文件')
    return value
class DocumentModel(models.Model):
    STATE_CHOICES = [
        ("1", "完成"),
        ("0", "未完成"),
    ]
    REPORT_TYPE_CHOICES = [
        ("2", "租赁合同"),
        ("1", "采购合同"),
        ("0", "销售合同"),
    ]
    TYPE_CHOICES = [
        ("2", "设计合同"),
        ("1", "设备合同"),
        ("0", "印刷合同"),
    ]
    orderId=models.CharField(max_length=50, verbose_name='合同编号', default='', null=True, blank=True, )
    detail = models.CharField(max_length=255, verbose_name='合同事项说明', default='', null=True, blank=True, )
    date = models.DateField(verbose_name='合同日期', default=timezone.now)  # 默认为当前时间
    type = models.CharField(max_length=50, verbose_name='类型', default='1', choices=TYPE_CHOICES)
    document_type = models.CharField(max_length=50, verbose_name='合同类型', default='1', choices=REPORT_TYPE_CHOICES)
    company = models.CharField(max_length=255, verbose_name='对方单位', default='', null=True, blank=True, )
    amount = models.DecimalField(verbose_name='合同金额', max_digits=10, decimal_places=4, default=0)
    tax = models.DecimalField(verbose_name='税率%', max_digits=3, decimal_places=0, default=9)

    state = models.CharField(max_length=50, verbose_name='状态', default='1', choices=STATE_CHOICES)

    remarks = models.CharField(max_length=50, verbose_name='备注', default='', null=True, blank=True, )
    # 普通文件上传
    report_name = models.CharField(max_length=50, verbose_name='文件名称', null=False, blank=True)

    # 先定义动态 upload_to 函数（关键）
    def dynamic_upload_path(instance, filename):
        """
        动态生成文件上传路径
        格式: uploads/files/report/[用户ID]/[应用标签]/[模型名称]/[文件名]
        """





        # 拼接路径（将特殊字符替换为下划线，避免路径错误）
        return f"uploads/document/{instance.type}/{filename}"

    report_file = models.FileField(upload_to=dynamic_upload_path,validators=[validate_file_size], verbose_name='文件')


    create_at = models.DateTimeField(verbose_name='创建日期', default=timezone.now)  # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)


    class Meta:
        verbose_name = '合同管理'
        verbose_name_plural = '合同管理'  # 自定义复数形式，与单数相同
    def __str__(self):
        return self.report_name
    def clean(self):
        """模型验证方法，用于检查保存条件"""

        if 'uploads/' not in self.report_file.name:
            self.report_name=self.report_file.name
        else:
            self.report_name = self.report_file.name.split('/')[-1]


# Create your models here.
class KnowledgeModel(models.Model):


    name = models.CharField(max_length=50, verbose_name='项目名称', default='',null=False, blank=False)

    content = RichTextUploadingField(verbose_name='内容')
    create_at = models.DateTimeField(verbose_name='创建日期', default=timezone.now)  # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)
    class Meta:
        verbose_name='内部知识'
        verbose_name_plural = '内部知识'  # 自定义复数形式，与单数相同
    def __str__(self):
        return self.name
class KnowledgeFileModel(models.Model):
    # 将原来的standard字符字段改为外键关联到StandardModel
    knowledge = models.ForeignKey(
        KnowledgeModel,
        on_delete=models.CASCADE,
        null=False,  # 数据库层面不允许为NULL
        blank=False,
        verbose_name='内部知识'
    )

    # 先定义动态 upload_to 函数（关键）
    def dynamic_upload_path(instance, filename):

        # 拼接路径（将特殊字符替换为下划线，避免路径错误）
        return f"uploads/files/document/knowledge/{instance.pk}/{filename}"
    file = models.ImageField(upload_to=dynamic_upload_path, validators=[validate_file_size],
                                   verbose_name='附件')


    create_at = models.DateTimeField(verbose_name='创建日期', default=timezone.now)  # 默认为当前时间
    # 更新时间：每次保存（包括首次）时自动更新为当前时间
    update_at = models.DateTimeField(verbose_name='更新日期', auto_now=True)

    class Meta:
        verbose_name = '附件'
        verbose_name_plural = '附件'  # 自定义复数形式，与单数相同